<template lang="pug">
  el-drawer.commonDrawer(
    :title="`${!id ? '新增' : '编辑'}退费`"
    :visible="visibleDialog"
    append-to-body
    center
    destroy-on-close
    direction="rtl"
    size="1120px"
    @close="$_handleCancel"
  )
    .drawer-content
      form-box(
        ref="form"
        :fields="fields"
        :showBtns="false"
        :layoutCol="{ xs: 24, md: 24, lg: 24 }"
        labelWidth="146px"
      )
        div(slot="form-client")
          el-button(type="primary" icon="el-icon-circle-plus" v-if="clients.length <= 0" round plain @click="addClients") 退费客户
          div(class="tag-div")
            el-tag(v-for="(tag, index) in clients" :key="index" class="tag-item" closable @close="deleteHandle(tag)") {{tag.name}}
        div(slot="form-items")
          el-button(type="primary" icon="el-icon-circle-plus" round plain @click="addProducts") 退费产品
          div(class="refund-product table-empty")
            s-table(
              ref="productTable"
              :column="productColumn2"
              v-if="productRecords.length > 0"
              :dataPops="productRecords"
            )
              template(slot="action" slot-scope="text, scope")
                el-link(@click="deleteProductHandle(scope.id)" type="primary") 删除
                el-link(@click="searchProductHandle(scope.id)" type="primary") 查询
              template(slot="refundAmount" slot-scope="text, scope")
                el-input-number.w(:value="text" controls-position="right" :min="1" @change="val => productFormChange(val, scope.id, 'refundAmount')")
              template(slot="remark" slot-scope="text, scope")
                el-input(:value="recommendRemark" controls-position="right" placeholder="请输入内容" @input="val => productFormChange(val, scope.id, 'remark')")
    .drawer-footer.tr
      el-button.gradientVertical(size="large" :loading="submitting" @click="submitHandle" round) 提交
    table-selector(@sureHandle="sureHandle" :visible.sync="clientsVisible" :value="value" :column="client.column" :search-config="client.searchConfig" label="客户" :single="true" req-url="crm/web/clientele/find")
    table-selector(
      @sureHandle="productSureHandle"
      :visible.sync="productVisible"
      :value="productValue"
      :column="productSelector.column"
      :search-config="productSelector.searchConfig"
      label="可退款产品"
      :single="false"
      req-url="crm/fin/refund_product/refundable_products"
      reqMethod="GET"
      :queryPropsParams="{clienteleId}"
      :showBtns="false"
    )
</template>

<script>
const productColumn2 = [
  {
    label: '产品名称',
    prop: 'productName'
  },
  {
    label: '单价',
    prop: 'practicalAmount'
  },
  {
    label: '数量',
    prop: 'count'
  },
  {
    label: '金额',
    prop: 'practicalTotalAmount'
  },
  {
    label: '退费金额',
    prop: 'refundAmount'
  },
  {
    label: '退费说明',
    prop: 'remark'
  },
  {
    label: '操作',
    prop: 'action'
  }
]
import TableSelector from '@/components/Basic/TableSelector'
import { clientColumn, seachConfigClient, productColumn } from '../config'
import { getClasses, addRefund, recommendRefund } from '../api'
export default {
  components: {
    TableSelector
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    childrenId: {
      type: String,
      default: ''
    },
    classesId: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    values: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      test: '',
      info: {},
      submitting: false,
      loading: false,
      clientsVisible: false,
      classes: [],
      clients: [],
      value: [],
      clienteleId: '',
      productVisible: false,
      productValue: [],
      productRecords: [],
      productColumn2,
      refundMoney: 0,
      recommendRemark: ''
    }
  },
  computed: {
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    client () {
      return {
        column: clientColumn,
        searchConfig: seachConfigClient(this.classes)
      }
    },
    productSelector () {
      return {
        column: productColumn,
        searchConfig: []
      }
    },
    fields () {
      const { info } = this
      console.log(info)
      return [
        {
          label: '选择客户',
          key: 'client',
          type: 'slot',
          initialValue: info?.client
        },
        {
          label: '选择产品',
          key: 'items',
          type: 'slot',
          initialValue: info?.items
        },
        {
          label: '退费时间',
          key: 'refundTime',
          type: 'date',
          formatFlag: true,
          rules: [{ required: true, message: '请选择' }],
          initialValue: info.refundTime
        },
        {
          label: '退费方式',
          key: 'refundType',
          type: 'select',
          rules: [{ required: true, message: '请选择' }],
          fieldProps: {
            options: [
              { id: '支付宝', name: '支付宝' },
              { id: '微信', name: '微信' },
              { id: '银行卡', name: '银行卡' }
            ],
            props: { value: 'id', label: 'name' }
          },
          initialValue: info.refundType
        },
        {
          label: '退费账号',
          key: 'refundAccountId',
          rules: [{ required: true, message: '请输入退费账号' }],
          initialValue: info.refundAccountId
        },
        {
          label: '流水号',
          key: 'serialNumber',
          rules: [{ required: true, message: '请输入流水号' }],
          initialValue: info.serialNumber
        }
      ]
    }
  },
  watch: {
    values: {
      handler (val) {
        this.info = val
      },
      immediate: true
    }
  },
  created () {
    this.getClassList()
  },
  methods: {
    async submitHandle () {
      if (this.clients.length === 0) {
        this.$message.warning('请先选择退费用户')
        return
      }
      if (this.productRecords.length === 0) {
        this.$message.warning('请添加退费产品')
        return
      }
      const values = await this.$refs.form.submitForm()
      const { clienteleId } = this
      const { childName } = this.clients[0]
      const items = this.productRecords.map(x => {
        return {
          amount: x.practicalTotalAmount,
          contractId: x.contractId,
          recordId: x.id,
          refundAmount: x.refundAmount,
          refundRemark: x.refundRemark,
          title: x.productName
        }
      })
      const params = {
        id: this.id,
        ...values,
        clienteleId,
        childName,
        items
      }
      addRefund(params).then(res => {
        if (res) {
          this.$message.success('保存成功')
          this.$emit('getList')
          this.$_handleCancel()
        }
      })
    },
    monthChange (res) {
    },
    $_handleCancel () {
      this.visibleDialog = false
    },
    addClients () {
      this.value = [...this.clients]
      this.clientsVisible = true
    },
    // 获取班级列表
    getClassList () {
      getClasses().then(res => {
        this.classes = res || []
      })
    },
    // 删除标签
    deleteHandle (tag) {
      const { clients } = this
      this.clients = [...clients.filter(x => x.id !== tag.id)]
      this.productRecords = []
    },
    sureHandle (data) {
      this.clients = data
      if (this.clients.length > 0) {
        this.clienteleId = this.clients[0].id
      }
    },
    addProducts () {
      if (this.clients.length === 0) {
        this.$message.info('请先选择退款客户')
        return
      }
      this.productValue = [...this.productRecords]
      this.productVisible = true
    },
    productSureHandle (data) {
      this.productRecords = data.map(x => {
        this.searchProductHandle(x.id)
        return x
      })
      this.standardAmount(this.productRecords)
    },
    // 删除选中意向产品
    deleteProductHandle (id) {
      const { productRecords } = this
      this.productRecords = productRecords.filter(x => x.id !== id)
    },
    searchProductHandle (id) {
      console.log('searchProductHandle')
      recommendRefund({ refundCPId: id, clienteleId: this.clienteleId }).then(res => {
        this.recommendRemark = res.recommendRemark
      })
    },
    productFormChange (val, id, key) {
      const { productRecords } = this
      this.productRecords = productRecords.map(x => {
        if (x.id === id) {
          x[key] = val
        }
        return x
      })
      console.log(this.productRecords)
      this.standardAmount(this.productRecords)
    },
    standardAmount (productRecords) {
      this.refundMoney = productRecords.reduce((sum, cur) => {
        console.log(cur)
        if (Object.prototype.hasOwnProperty.call(cur, 'refundAmount')) {
          return sum + cur.refundAmount
        }
        return sum
      }, 0)
      console.log(this.refundMoney)
    }
  }
}
</script>

<style lang="scss" scoped>
.refund-product{
  margin-top: 20px;
}
.tag-div{
  // margin-top: 10px;
  .tag-item{
    margin-right: 10px;
    margin-top: 10px;
  }
}
.clientSelector{
  margin-bottom: 20px;
}
</style>
